<?php

include 'dbinfo.php';
include 'opendb.php';
echo' <link rel="stylesheet" type="text/css" href="css/style.css" />';

echo "<div align='left'><form action='gointerns_backup.php' method='post'><input type='submit' name='createBackup' value='Create Backup' class='submit' /></form></div><br />";

if (isset($_POST['restoreButton'])) {
    restoreBackup($db_hostname, $db_username, $db_password, $db_name);
}
if (isset($_POST['createBackup'])) {
    createBackup($db_hostname, $db_username, $db_password, $db_name);
}

echo "<table width='400px' cellspacing=0>";
echo "<tr><td><h2>Backups</h2></td></tr>";
echo "<tr><td colspan=2><hr /></td></tr>";
getDirectoryList('backups/');
echo "</table>";

include 'closedb.php';

function restoreBackup($db_hostname, $db_username, $db_password, $db_name) {
    $filename = $_POST['restoreBackup'];
    $result = mysql_query("drop database $db_name");
    $result = mysql_query("create database $db_name");
    if ($db_password == '') {
        $command = "mysql -h $db_hostname -u $db_username $db_name < backups\\$filename";
    } else {
        $command = "mysql -h $db_hostname -u $db_username -p $db_password $db_name < backups\\$filename";
    }
    system($command, $error);
    if ($error) {
        echo "Could not restore from backup...";
    } else {
        echo "<div align='left'>";
        echo "<h2>Backup successfully restored!</h2>";
        echo "<hr />";
        echo "<a href='index.php'>Back to the database</a>";
        echo "</div>";
        die;
    }
}

function createBackup($db_hostname, $db_username, $db_password, $db_name) {

    $backupFile = date('Y-m-d-H-i-s') . '.sql';
    if ($db_password == '') {
        $command = "mysqldump -h $db_hostname -u $db_username $db_name > backups\\$backupFile";
    } else {
        $command = "mysqldump -h $db_hostname -u $db_username -p $db_password $db_name > backups\\$backupFile";
    }
    system($command, $error);
    if ($error
        )die("<h1>Backup failed!</h1>");
    echo "<div align='left'><h1>Backup successfully created!</h1></div>";
}

function getDirectoryList($directory) {

    $results = array();
    $handler = opendir($directory);
    $i = 0;
    while ($file = readdir($handler)) {
        if ($file != "." && $file != "..") {
            $i++;
            if ($i % 2 == 0) {
                echo "<tr bgcolor='#FBFBFB'>";
            } else {
                echo "<tr>";
            }
            echo "<td valign='middle' align='center'>";
            echo "<form action='gointerns_backup.php' method='post'>";
            echo "<input type='hidden' name='restoreBackup' value='$file' />";
            echo "$file</td><td><input type='submit' class='submit' name='restoreButton' value='RESTORE' />";
            echo "</form></td></tr>";
        }
    }
    closedir($handler);
}

?>